<template>
  <div class="banner-management">
    <!-- 当前Banner展示 -->
    <el-card class="current-banner" shadow="hover">
      <template #header>
        <div class="card-header">
          <span class="title">当前展示的Banner</span>
        </div>
      </template>
      <el-image
          v-if="currentBanner"
          :src="currentBanner.bannerImg"
          fit="cover"
          class="banner-image"
      >
        <template #error>
          <div class="image-slot">
            <el-icon><Picture /></el-icon>
          </div>
        </template>
      </el-image>
      <div v-else class="empty-banner">
        <el-icon><Promotion /></el-icon>
        <span>当前没有正在展示的Banner</span>
      </div>
    </el-card>

    <!-- Banner管理工具栏 -->
    <div class="management-toolbar">
      <el-button
          type="primary"
          :icon="Plus"
          @click="handleAdd"
      >
        新建Banner
      </el-button>
      <el-button
          type="info"
          :icon="Refresh"
          @click="fetchBannerList"
      >
        刷新列表
      </el-button>
    </div>

    <!-- Banner数据表格 -->
    <el-table
        :data="tableData"
        stripe
        style="width: 100%"

        row-key="id"
    >
<!--      v-loading="loading"-->
      <el-table-column prop="bannerId" label="ID" width="80" align="center"/>
      <el-table-column label="Banner图" width="170" align="center">
        <template #default="{ row }">
          <el-image
              :src="row.bannerImg"
              fit="cover"
              class="table-image"
          />
<!--          :preview-src-list="[row.image]"-->
        </template>
      </el-table-column>
      <el-table-column prop="bannerTitle" label="标题" width="150" align="center"/>
      <el-table-column prop="bannerImg" label="跳转链接" show-overflow-tooltip width="130" align="center"/>
      <el-table-column prop="bannerType" label="banner类型" width="120" align="center">
        <template #default="{ row }">
          <el-tag
          :type="row.bannerType === 1 ? 'success' : 'primary'"
          effect="dark"
          >
            {{ row.bannerType === 1 ? '首页banner' : '用户空间banner' }}
          </el-tag>
        </template>
      </el-table-column>
<!--      <el-table-column label="状态" width="120">-->
<!--        <template #default="{ row }">-->
<!--          <el-tag-->
<!--              :type="row.status === 1 ? 'success' : 'danger'"-->
<!--              effect="dark"-->
<!--          >-->
<!--            {{ row.status === 1 ? '启用中' : '已禁用' }}-->
<!--          </el-tag>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column prop="createTime" label="创建时间" width="160" align="center"/>
      <el-table-column prop="updateTime" label="修改时间" width="160" align="center"/>
      <el-table-column label="操作" width="220" fixed="right">
        <template #default="{ row }">
          <el-button
              size="small"
              type="primary"
              :icon="Edit"
              @click="handleEdit(row)"
          >
            编辑
          </el-button>
          <el-button
              size="small"
              type="danger"
              :icon="Delete"
              @click="handleDelete(row.id)"
          >
            删除
          </el-button>
          <el-button
              v-if="currentBanner?.id !== row.id"
              size="small"
              type="success"
              :icon="Star"
              @click="setCurrentBanner(row)"
          >
            设为当前
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- Banner编辑对话框 -->
    <el-dialog
        v-model="dialogVisible"
        :title="isEdit ? '编辑Banner' : '新建Banner'"
        width="40%"
        destroy-on-close
    >
      <el-form
          ref="formRef"
          :model="formData"
          label-width="100px"
          :rules="formRules"
      >
        <el-form-item label="标题" prop="title">
          <el-input v-model="formData.title" />
        </el-form-item>
        <el-form-item label="跳转链接" prop="link">
          <el-input v-model="formData.link" />
        </el-form-item>
        <el-form-item label="Banner图" prop="image">
          <el-upload
              class="banner-upload"
              action="#"
              :show-file-list="false"
              :auto-upload="false"
              :on-change="handleImageChange"
          >
            <el-button type="primary">点击上传</el-button>
            <template #tip>
              <div class="upload-tip">
                建议尺寸：1920×400px，大小不超过5MB
              </div>
            </template>
          </el-upload>
          <el-image
              v-if="formData.image"
              :src="formData.image"
              class="preview-image"
          />
        </el-form-item>

      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">
          确认
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import {
  Plus,
  Edit,
  Delete,
  Star,
  Refresh,
  Picture,
  Promotion
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {bannerPageQuery} from "@/api/admin-api.js";

// 模拟数据
const mockData = [
  {
    id: 1,
    title: '夏日活动',
    link: '/activity/summer',
    image: 'https://demo.banner.com/1.jpg',
    status: 1,
    create_time: '2023-07-15 14:00:00'
  },
  // 更多模拟数据...
]
const bannerData = ref([
  {
    bannerId:1,
    bannerImg:'https://demo.banner.com/1.jpg',
    bannerTitle:'夏日活动',
    bannerType:1,
    currentUse:1,
    createTime:'2023-07-15 14:00:00',
    updateTime:'2023-07-15 14:00:00',
  }
])

// 响应式数据
const currentBanner = ref()
// const tableData = ref([...mockData])
const tableData = ref([])
const loading = ref(false)
const dialogVisible = ref(false)
const isEdit = ref(false)
const formRef = ref()
const formData = reactive({
  id: null,
  title: '',
  link: '',
  image: '',
  status: 1
})

// 表单验证规则
const formRules = {
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  link: [
    { required: true, message: '请输入跳转链接', trigger: 'blur' },
    { type: 'url', message: '请输入正确的URL地址', trigger: 'blur' }
  ],
  image: [{ required: true, message: '请上传Banner图片', trigger: 'change' }]
}


const queryParam = reactive({
  name:'',
  page:1,
  size:9,
})

const fetchBannerList = async () => {
  loading.value = true
  try {
    const res = await bannerPageQuery(queryParam)
    tableData.value = res.data.records
    for (let i = 0; i < tableData.value.length; i++) {
      if(tableData.value[i].currentUse === 1){
        currentBanner.value = tableData.value[i];
        break
      }
    }

    // ElMessage.success('加载数据成功')
  } catch (error) {
    ElMessage.error('加载数据失败' + error.message)
  }

  // 模拟API调用
  // setTimeout(() => {
  //   tableData.value = mockData
  //   loading.value = false
  // }, 800)
}

const handleAdd = () => {
  isEdit.value = false
  Object.assign(formData, {
    id: null,
    title: '',
    link: '',
    image: '',
    status: 1
  })
  dialogVisible.value = true
}

const handleEdit = (row) => {
  isEdit.value = true
  Object.assign(formData, { ...row })
  dialogVisible.value = true
}

const handleDelete = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除该Banner吗？', '警告', {
      type: 'warning',
      confirmButtonText: '确认',
      cancelButtonText: '取消'
    })
    tableData.value = tableData.value.filter(item => item.id !== id)
    ElMessage.success('删除成功')
  } catch {
    // 用户取消操作
  }
}

const setCurrentBanner = (banner) => {
  currentBanner.value = banner
  ElMessage.success('已更新当前展示的Banner')
}

const handleImageChange = (file) => {
  // 这里处理图片上传逻辑，演示用本地预览
  const reader = new FileReader()
  reader.onload = (e) => {
    formData.image = e.target.result
  }
  reader.readAsDataURL(file.raw)
}

const submitForm = async () => {
  try {
    await formRef.value.validate()

    if (isEdit.value) {
      // 更新逻辑
      const index = tableData.value.findIndex(item => item.id === formData.id)
      tableData.value.splice(index, 1, { ...formData })
    } else {
      // 新增逻辑
      const newBanner = {
        ...formData,
        id: Date.now(),
        create_time: new Date().toLocaleString()
      }
      tableData.value.unshift(newBanner)
    }

    dialogVisible.value = false
    ElMessage.success(isEdit.value ? '修改成功' : '新增成功')
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

// 生命周期钩子
onMounted(() => {
  fetchBannerList()
})
</script>

<style scoped>
.current-banner {
  margin-bottom: 20px;
}

.banner-image {
  width: 100%;
  height: 200px;
  border-radius: 4px;
}

.empty-banner {
  height: 200px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: var(--el-color-info);
}

.empty-banner .el-icon {
  font-size: 48px;
  margin-bottom: 10px;
}

.management-toolbar {
  margin-bottom: 20px;
}

.table-image {
  width: 160px;
  height: 60px;
  border-radius: 4px;
}

.preview-image {
  margin-top: 10px;
  max-width: 100%;
  max-height: 200px;
}

.upload-tip {
  color: var(--el-text-color-secondary);
  font-size: 12px;
  margin-top: 5px;
}
</style>